package com.market.plus.controller.validator;

import java.awt.Dimension;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.market.plus.controller.model.ContentFileInstance;
import com.market.plus.core.dto.AlbumDto;
import com.market.plus.core.exception.MarketRuntimeException;
import com.market.plus.core.util.MarketUtil;
import com.market.plus.ocm.service.SimpleImageInfo;

@Component("fileValidator")
public class FileValidator implements Validator {

   public boolean supports(Class<?> object) {
      return ContentFileInstance.class.isAssignableFrom(object);
   }

   public void validate(Object object, Errors errors) {
      validateObject(object, errors);
   }

   public void validateObject(Object object, Errors errors) {
      ContentFileInstance contentFileInstance = (ContentFileInstance) object;
      AlbumDto albumDto = contentFileInstance.getAlbum();
      if (albumDto == null || MarketUtil.hasEmptyOrNull(albumDto.getAlbumGUID())){
         errors.rejectValue("album.albumGUID", "err.required");
      }

      if (contentFileInstance.getFileData().getSize() < 10000){
         errors.rejectValue("fileData", "err.file.length");
      }

      try {
         Dimension dimension = SimpleImageInfo.processStream(contentFileInstance.getFileData().getInputStream());
         if (dimension.height < 149 || dimension.width < 200){
            errors.rejectValue("fileData", "err.file.size.invalid");
         }
      } catch (Exception exception){
         throw new MarketRuntimeException(exception);
      }
   }
}
